package com.summer.data.springboot;

import com.summer.data.table.BaseColumn;
import com.summer.data.table.BaseTable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.lang.reflect.Field;

@JsonComponent
public class TableJsonSerializer extends StdSerializer<BaseTable> {

    protected TableJsonSerializer() {
        super(BaseTable.class);
    }

    @Override
    public void serialize(BaseTable table, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        try {
            jsonGenerator.writeStartObject();

            Class<? extends BaseTable> clazz = table.getClass();
            for (Field field : clazz.getFields()) {
                // JsonIgnore  不用输出
                JsonIgnore jsonIgnore = field.getAnnotation(JsonIgnore.class);
                if (jsonIgnore != null) {
                    continue;
                }

                Object fieldInstance = field.get(table);
                String jsonFieldName = field.getName();
                // 如果设定 JsonProperty，使用 JsonProperty 设定值
                JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
                if (jsonProperty != null) {
                    jsonFieldName = jsonProperty.value();
                }

                if (fieldInstance instanceof BaseColumn<?>) {
                    BaseColumn col = (BaseColumn) fieldInstance;
                    jsonGenerator.writeObjectField(jsonFieldName, col.getValue());
                }
            }
            jsonGenerator.writeEndObject();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
